package xuhaijia.lanou3g.autohome.myself;
//                .-~~~~~~~~~-._       _.-~~~~~~~~~-.
//            __.'              ~.   .~              `.__
//          .'//                  \./                   \\`.
//        .'//            为什么坚持  想一想当初             \\`.
//      .'// .-~"""""""~~~~-._     |     _,-~~~~"""""""~-.  \\`.
//    .'//.-"                 `-.  |  .-'                 "-. \\`.
//  .'//______.============-..   \ | /   ..-============._______\\`.
//.'//____________________________\|/_____________________________\\`.
// 
//                             

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.mob.tools.utils.UIHandler;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.HashMap;
import java.util.zip.Inflater;

import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.UpdateListener;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import xuhaijia.lanou3g.autohome.R;
import xuhaijia.lanou3g.autohome.activity.CircleJumpActivity;
import xuhaijia.lanou3g.autohome.base.BaseFragment;
import xuhaijia.lanou3g.autohome.base.MyApp;


/**
 * Created by dllo on 16/8/15.
 */
public class MyselfFragment extends BaseFragment implements View.OnClickListener {

    private LinearLayout ll;
    private View noEnterView;
    private View enterView;
    private ImageView iconIv;
    private TextView nameTv;
    private LinearLayout accountLogin;
    private LinearLayout twitterLogin;
    private TextView loginTv;
    private TextView upFromMap;
    private TextView upFromCamera;
    private String IMAGE_UNSPECIFIED = "image/*";
    private final int ALBUM_REQUEST_CODE = 1;
    private final int CAMERA_REQUEST_CODE = 2;
    private final int CROP_REQUEST_CODE = 4;
    private String TAG = "EnterSuccess";
    private AutoHomeUser autoHomeUser;
    private Dialog mLoginingDlg;
    private TextView changeAc;
    private TextView logout;
    private RelativeLayout replace;
    private RelativeLayout coupon;
    private RelativeLayout collection;
    private RelativeLayout history;
    private RelativeLayout draft;
    private RelativeLayout set;
    private Intent intentClo;

    @Override
    protected int setLayout() {
        return R.layout.fragment_myself;
    }

    @Override
    protected void initView() {

        ll = bindView(R.id.fragment_myself_loginll);
        noEnterView = LayoutInflater.from(mContext).inflate(R.layout.no_enter, null);
        loginTv = (TextView) noEnterView.findViewById(R.id.myself_login);
        accountLogin = (LinearLayout) noEnterView.findViewById(R.id.account_login);
        twitterLogin = (LinearLayout) noEnterView.findViewById(R.id.twitter_login);
        enterView = LayoutInflater.from(mContext).inflate(R.layout.enter_success, null);
        iconIv = (ImageView) enterView.findViewById(R.id.enter_success_icon);
        nameTv = (TextView) enterView.findViewById(R.id.enter_success_name);
        upFromMap = (TextView) enterView.findViewById(R.id.enter_success_updatefrommap);
        upFromCamera = (TextView) enterView.findViewById(R.id.enter_success_updatefromcamera);
        changeAc = (TextView) enterView.findViewById(R.id.enter_success_changeac);
        logout = (TextView) enterView.findViewById(R.id.enter_success_logout);
        replace = bindView(R.id.myself_replace);
        coupon = bindView(R.id.myself_coupon);
        collection = bindView(R.id.myself_collection);
        history = bindView(R.id.myself_history);
        draft = bindView(R.id.myself_draft);
        set = bindView(R.id.myself_set);
        iconIv.setOnClickListener(this);
        loginTv.setOnClickListener(this);
        accountLogin.setOnClickListener(this);
        twitterLogin.setOnClickListener(this);
        replace.setOnClickListener(this);
        coupon.setOnClickListener(this);
        collection.setOnClickListener(this);
        history.setOnClickListener(this);
        draft.setOnClickListener(this);
        set.setOnClickListener(this);
        upFromCamera.setOnClickListener(this);
        upFromMap.setOnClickListener(this);
        changeAc.setOnClickListener(this);
        logout.setOnClickListener(this);
    }

    @Override
    protected void initData() {

    }


    @Override
    public void load() {

    }

    @Override
    public void refresh() {

    }



    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.myself_login:
                Intent intent = new Intent(getContext(), LoginActivity.class);
                startActivity(intent);
                break;
            case R.id.account_login:
                Intent intentAc = new Intent(getContext(), LoginActivity.class);
                startActivity(intentAc);
                break;
            case R.id.twitter_login:
                ShareSDK.initSDK(mContext);
                Platform weibo = ShareSDK.getPlatform(SinaWeibo.NAME);
                weibo.setPlatformActionListener(new PlatformActionListener() {
                    @Override
                    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                        Toast.makeText(mContext, "授权成功", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(Platform platform, int i, Throwable throwable) {
                        Toast.makeText(mContext, "授权失败", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onCancel(Platform platform, int i) {
                        Toast.makeText(mContext, "授权取消", Toast.LENGTH_SHORT).show();
                    }
                });
                weibo.authorize();//单独授权
//                weibo.showUser(null);//授权并获取用户信息
//authorize与showUser单独调用一个即可
//移除授权
//weibo.removeAccount(true);


                break;
            case R.id.enter_success_updatefrommap:
                Intent intentMap = new Intent(Intent.ACTION_PICK, null);
                intentMap.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_UNSPECIFIED);
                startActivityForResult(intentMap, ALBUM_REQUEST_CODE);
                initLoginingDlg();
                break;
            case R.id.enter_success_updatefromcamera:
                Intent intentCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.
                        getExternalStorageDirectory(), "temp.jpg")));
                startActivityForResult(intentCamera, CAMERA_REQUEST_CODE);
                initLoginingDlg();
                break;
            case R.id.myself_replace:
                noEnterPlzEnter();
                break;
            case R.id.myself_collection:
                autoHomeUser = AutoHomeUser.getCurrentUser(AutoHomeUser.class);
                if (autoHomeUser == null) {
                    intentClo = new Intent(getContext(), LoginActivity.class);
                    startActivity(intentClo);
                } else {
                    intentClo = new Intent(getContext(), CollectionActivity.class);
                    startActivity(intentClo);
                }
                break;
            case R.id.myself_history:
                Intent intentHistory = new Intent(getContext(), HistoryActivity.class);
                startActivity(intentHistory);
                break;
            case R.id.myself_coupon:
                noEnterPlzEnter();
                break;
            case R.id.myself_draft:
                noEnterPlzEnter();
                break;
            case R.id.myself_set:
                Intent intentSet = new Intent(getContext() , CircleJumpActivity.class);
                startActivity(intentSet);
                break;
            case R.id.enter_success_changeac:

                autoHomeUser.logOut();
                noEnterPlzEnter();
                break;
            case R.id.enter_success_logout:
                autoHomeUser.logOut();
                isEnter();
                break;

        }
    }


    @Override
    public void onResume() {
        super.onResume();
        isEnter();
    }

    public void noEnterPlzEnter() {
        autoHomeUser = AutoHomeUser.getCurrentUser(AutoHomeUser.class);
        if (autoHomeUser == null) {
            Intent intent = new Intent(getContext(), LoginActivity.class);
            startActivity(intent);
        }
    }

    public void isEnter() {
        autoHomeUser = AutoHomeUser.getCurrentUser(AutoHomeUser.class);
        if (autoHomeUser != null) {
            if (autoHomeUser.getIcon() == null) {
                iconIv.setImageResource(R.mipmap.no_icon);
            } else {
                iconIv.setImageBitmap(autoHomeUser.getIcon());
            }
            ll.removeAllViews();
            nameTv.setText(autoHomeUser.getUsername());
            ll.addView(enterView);
        } else {
            ll.removeAllViews();
            ll.addView(noEnterView);
        }
    }

    /**
     * 开始裁剪
     *
     * @param uri
     */
    private void startCrop(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");//调用Android系统自带的一个图片剪裁页面,
        intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
        intent.putExtra("crop", "true");//进行修剪
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, CROP_REQUEST_CODE);
    }

    /**
     * 判断sdcard卡是否可用
     *
     * @return 布尔类型 true 可用 false 不可用
     */
    private boolean isSDCardCanUser() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case ALBUM_REQUEST_CODE:
//                Log.i(TAG, "相册，开始裁剪");
//                Log.i(TAG, "相册 [ " + data + " ]");
                if (data == null) {
                    return;
                }
                startCrop(data.getData());
                break;
            case CAMERA_REQUEST_CODE:
//                Log.i(TAG, "相机, 开始裁剪");
                File picture = new File(Environment.getExternalStorageDirectory()
                        + "/temp.jpg");
                startCrop(Uri.fromFile(picture));
                break;
            case CROP_REQUEST_CODE:
//                Log.i(TAG, "相册裁剪成功");
//                Log.i(TAG, "裁剪以后 [ " + data + " ]");
                if (data == null) {
                    // TODO 如果之前以后有设置过显示之前设置的图片 否则显示默认的图片
                    return;
                }
                Bundle extras = data.getExtras();
                if (extras != null) {
                    showLoginingDlg();
                    Bitmap photo = extras.getParcelable("data");
                    autoHomeUser.setIcon(photo);
                    autoHomeUser.update(new UpdateListener() {
                        @Override
                        public void done(BmobException e) {
                            if (e != null) {
                                Toast.makeText(mContext, "图片上传失败", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(mContext, "图片上传成功", Toast.LENGTH_SHORT).show();
                                isEnter();
                                closeLoginingDlg();
                            }
                        }
                    });
                }
                break;
            default:
                break;
        }
    }

    /* 初始化正在登录对话框 */
    private void initLoginingDlg() {
        mLoginingDlg = new Dialog(getContext(), R.style.loginingDlg);
        mLoginingDlg.setContentView(R.layout.logining_dlg);

    }

    private void showLoginingDlg() {
        if (mLoginingDlg != null)
            mLoginingDlg.show();
    }

    /* 关闭正在登录对话框 */
    private void closeLoginingDlg() {
        if (mLoginingDlg != null && mLoginingDlg.isShowing())
            mLoginingDlg.dismiss();
    }
}
